package com.tj.jinzao.fragment;

import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.netease.nim.uikit.api.NimUIKit;
import com.netease.nim.uikit.business.session.emoji.MoonUtil;
import com.netease.nim.uikit.video.jzvd.JzvdStd;
import com.tj.jinzao.App;
import com.tj.jinzao.R;
import com.tj.jinzao.activity.ArticleDetailActivity;
import com.tj.jinzao.activity.ImageActivity;
import com.tj.jinzao.activity.PersonArticleActivity;
import com.tj.jinzao.adapter.ArticleDeaAdapter;
import com.tj.jinzao.adapter.ArticleDetailListItemAdapter;
import com.tj.jinzao.api.ApiRetrofit;
import com.tj.jinzao.api.ApiService;
import com.tj.jinzao.api.SubscriberCallBack;
import com.tj.jinzao.base.BaseDataListFragment;
import com.tj.jinzao.callback.IArticleView;
import com.tj.jinzao.common.Constant;
import com.tj.jinzao.manager.UserManager;
import com.tj.jinzao.model.Article;
import com.tj.jinzao.model.Comment;
import com.tj.jinzao.model.ResultResponse;
import com.tj.jinzao.model.User;
import com.tj.jinzao.presenter.CommentPresenter;
import com.tj.jinzao.utils.ToastUtils;
import com.tj.jinzao.utils.Utils;
import com.tj.jinzao.video.MyJzvdStd;
import com.tj.jinzao.widgets.CommentDialog;
import com.tj.jinzao.widgets.MyImageSwitcher;
import com.tj.jinzao.widgets.MyListView;
import com.tj.jinzao.widgets.RoundedImageView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * 社区文章详情列表
 * Created by wjy on 2019/1/1.
 */
public class ArticleDetailListFragment extends BaseDataListFragment<Article, CommentPresenter, Comment> implements IArticleView<Article>, CommentDialog.OnSendListener {

    public final static int TYPE_DAILY = 1;
    public final static int TYPE_TOPIC = 2;

    private final static String ARG_DATA = "data";

    @BindView(R.id.tv_praise)
    TextView mPraiseView;
    @BindView(R.id.tv_comment)
    TextView mCommentView;
    @BindView(R.id.tv_collect)
    TextView mCollectView;
    private RoundedImageView mHeadView;
    private TextView mNameView;
    private TextView mVipView;
    private TextView mLabelView;
    private TextView mDateView;
    private TextView mFollowView;
    private TextView mSeeView;
    private TextView mReplyView;


    private Drawable mPraise, mPraised, mCollect, mCollected;

    private Article mArticle;

    private View mListHeadView;
    private View mListFootView;
    public static ArticleDetailListFragment newInstance(Article article) {
        ArticleDetailListFragment fragment = new ArticleDetailListFragment();
        if (fragment != null) {
            Bundle args = new Bundle(3);
            args.putString(ARG_TAG_ID, String.valueOf(1));
            args.putInt(ARG_LOAD_ID, 1);
            args.putSerializable(ARG_DATA, article);
            args.putInt(ARG_LAYOUT_RES_ID, R.layout.fragment_article_detail);
            fragment.setArguments(args);
        }
        return fragment;
    }

    @Override
    public void onRequestNoData(String message) {
        setEmptyDataView();
    }
   private ArticleDeaAdapter adapter;
    private MyListView my_list;
    private List<Article> list=new ArrayList<>();

    @Override
    protected CommentPresenter createPresenter() {
        return new CommentPresenter(this);
    }
    int type;
    @Override
    protected void createView(LayoutInflater inflater, View view) {
        mArticle = (Article) getArguments().getSerializable(ARG_DATA);
        type = mArticle.getType();
        Resources resources = getResources();
        mPraise = resources.getDrawable(R.mipmap.article_praise);
        mPraise.setBounds(0, 0, mPraise.getMinimumWidth(), mPraise.getMinimumHeight());
        mPraised = resources.getDrawable(R.mipmap.article_praised);
        mPraised.setBounds(0, 0, mPraised.getMinimumWidth(), mPraised.getMinimumHeight());
        mCollect = resources.getDrawable(R.mipmap.article_collect);
        mCollect.setBounds(0, 0, mCollect.getMinimumWidth(), mCollect.getMinimumHeight());
        mCollected = resources.getDrawable(R.mipmap.article_collected);
        mCollected.setBounds(0, 0, mCollected.getMinimumWidth(), mCollected.getMinimumHeight());

        switch (type) {
            case TYPE_TOPIC: {
                mListHeadView = inflater.inflate(R.layout.head_article_topic, null);
                break;
            }
            case TYPE_DAILY: {
                mListHeadView = inflater.inflate(R.layout.head_article_daily, null);
                mListHeadView.findViewById(R.id.tv_left).setOnClickListener(this);
                mListHeadView.findViewById(R.id.tv_right).setOnClickListener(this);
                break;
            }
        }
        mListFootView = inflater.inflate(R.layout.layout_bottom, null);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mListHeadView.setLayoutParams(params);
        mListFootView.setLayoutParams(params);
        mHeadView = mListHeadView.findViewById(R.id.iv_head);
        my_list = mListFootView.findViewById(R.id.my_list);
        mNameView = mListHeadView.findViewById(R.id.tv_name);
        mVipView = mListHeadView.findViewById(R.id.tv_vip);
        mLabelView = mListHeadView.findViewById(R.id.tv_label);
        mDateView = mListHeadView.findViewById(R.id.tv_date);
        mFollowView = mListHeadView.findViewById(R.id.tv_follow);
        mReplyView = mListHeadView.findViewById(R.id.tv_comment);
        mSeeView = mListHeadView.findViewById(R.id.tv_view);
        mFollowView.setOnClickListener(this);
        mListView.addHeaderView(mListHeadView);
//        if(type==TYPE_DAILY){
            mListView.addFootView(mListFootView);
//        }
        mListView.setFocusable(true);

    }
    protected ApiService mApiService = ApiRetrofit.getInstance().getApiService();

    private CompositeSubscription mCompositeSubscription;


    public void detachView() {
        onUnsubscribe();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        detachView();
    }
    public void addSubscription(Observable observable, Subscriber subscriber) {
        if (mCompositeSubscription == null) {
            mCompositeSubscription = new CompositeSubscription();
        }
        mCompositeSubscription.add(observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber));
    }

    //RXjava取消注册，以避免内存泄露
    public void onUnsubscribe() {
        if (mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) {
            mCompositeSubscription.unsubscribe();
        }
    }


    @Override
    protected void setupViews(LayoutInflater inflater, View view) {
        super.setupViews(inflater, view);
//        if(type==TYPE_DAILY){
            mArticle = (Article) getArguments().getSerializable(ARG_DATA);
            if(mArticle==null){
                return;
            }
            HashMap<String, Object> map = new HashMap();
            map.put("id", mArticle.getId());
            long uId = UserManager.getInstance().getUser().getId();
            map.put("loginUid", uId);
            addSubscription(mApiService.getArticleListTJ(map), new SubscriberCallBack<List<Article>>(getActivity()) {
                @Override
                protected void onSuccess(List<Article> list) {
                    adapter=new ArticleDeaAdapter(getActivity(),list,false);
                    my_list.setAdapter(adapter);
                    my_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                            if(list!=null&&list.size()>0){
                                getActivity().finish();
                                startActivity(new Intent(mContext, ArticleDetailActivity.class).putExtra("article", list.get(i)));
                            }
                        }
                    });


                }

                @Override
                protected void onFailure(ResultResponse response) {
                }

                @Override
                protected boolean isShowProgress() {
                    return false;
                }

                @Override
                protected void onPageSuccess(int currentPage, int allPage, int allSize) {
                }
            });

//        }


    }

    private void bindData() {
        mPraiseView.setText(String.valueOf(mArticle.getLike()));
        mPraiseView.setCompoundDrawables(mArticle.isHasLike() ? mPraised : mPraise, null, null, null);
        mCollectView.setText(String.valueOf(mArticle.getCollectionCount()));
        mCollectView.setCompoundDrawables(mArticle.isHasCollection() ? mCollected : mCollect, null, null, null);
        mCommentView.setText(String.valueOf(mArticle.getComment()));
        final User user = mArticle.getUser();
        mHeadView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(user!=null){
                    startActivity(new Intent(mContext, PersonArticleActivity.class)
                            .putExtra("user", user));


                }
            }
        });
        Glide.with(this).load(Constant.IMAGE_PREFIX + user.getImgurl()).into(mHeadView);
        mNameView.setText(user.getNickname());
        mVipView.setText("V" + user.getLevel());
        mLabelView.setText(mArticle.getTag());
        mDateView.setText(mArticle.getReleaseTime());
        mFollowView.setText(mArticle.isHasFollowCircle() ? "已关注" : "关注");
        mFollowView.setActivated(mArticle.isHasFollowCircle());
        mFollowView.setTextColor(Color.parseColor(mArticle.isHasFollowCircle() ? "#ffb9bdd2" : "#ff00c08d"));
        mSeeView.setText(mArticle.getView() + "人已看");
        mReplyView.setText(mArticle.getComment() + "条");
        switch (mArticle.getType()) {
            case TYPE_TOPIC: {
                LinearLayout linearLayout = mListHeadView.findViewById(R.id.ll_content_layout);
                mListHeadView.findViewById(R.id.ll_next_layout).setVisibility(View.GONE);
                String images = mArticle.getImgurls();
                List<String> list = new ArrayList();
                if (!TextUtils.isEmpty(images)) {
                    String imageArray[] = images.split(",");
                    list = Arrays.asList(imageArray);
                }
                mPresenter.setShowContentView(getLayoutInflater(), mArticle.getContent(), list, mArticle.isVideo(), mArticle.getVideoUrl(),linearLayout, this);
                break;
            }
            case TYPE_DAILY: {
                ImageView imageView = mListHeadView.findViewById(R.id.iv_image);
                RelativeLayout rl_image_layout = mListHeadView.findViewById(R.id.rl_image_layout);
               MyJzvdStd jcVideoPlayerStandard = view.findViewById(R.id.videoplayer);
                if (!mArticle.isVideo()) {
                    imageView.setVisibility(View.VISIBLE);
                    initBanner(mListHeadView);
                    jcVideoPlayerStandard.setVisibility(View.GONE);
                } else {
                    jcVideoPlayerStandard.setVisibility(View.VISIBLE);
                    jcVideoPlayerStandard.setUp(Constant.IMAGE_PREFIX+mArticle.getVideoUrl()
                            , "", JzvdStd.SCREEN_NORMAL);
                    if(mArticle.getImgurls()!=null&&mArticle.getImgurls().contains(",")){
                        String images[] = mArticle.getImgurls().split(",");
                        Glide.with(this).load(Constant.IMAGE_PREFIX + images[0]).into(jcVideoPlayerStandard.thumbImageView);
                    }else {
                        Glide.with(this).load(Constant.IMAGE_PREFIX + mArticle.getImgurls()).into(jcVideoPlayerStandard.thumbImageView);
                    }
                    imageView.setVisibility(View.GONE);
                    imageView.setOnClickListener(this);
                    imageView.setTag(R.id.position, 0);
                    int width = Constant.SCREEN_WIDTH - Utils.dpToPx(40, getResources());
                    int height = width * 157 / 330;
                    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(width, height);
                    params.setMargins(Utils.dpToPx(20, getResources()), Utils.dpToPx(10, getResources()), Utils.dpToPx(20, getResources()), 0);
                    imageView.setLayoutParams(params);
                    if(mArticle.getImgurls()==null||mArticle.getImgurls().equals("")){
                        imageView.setVisibility(View.GONE);
                    }else {
                        imageView.setVisibility(View.VISIBLE);
                    }

                    Glide.with(mContext).load(Constant.IMAGE_PREFIX + mArticle.getImgurls()).into(imageView);
                }
                TextView textView = mListHeadView.findViewById(R.id.tv_text_1);
                MoonUtil.identifyFaceExpression(NimUIKit.getContext(), textView
                        , mArticle.getContent()
                                .replace(Constant.ARTICLE_P1,"")
                                .replace(Constant.ARTICLE_P2,"")
                                .replace(Constant.ARTICLE_TAG, "")
                        , ImageSpan.ALIGN_BOTTOM);
                break;
            }
        }
    }

    protected MyImageSwitcher mSwitcher;

    protected void initBanner(View view) {
        mSwitcher = view.findViewById(R.id.image_switcher);
        mSwitcher.setVisibility(View.VISIBLE);
        mSwitcher.setAnimations(R.anim.anim_in_alpha, R.anim.anim_out_alpha);
        mSwitcher.setPadding(0, 0, 0, 0);
        mSwitcher.setOnClickListener(this);
        LinearLayout dotLayout = view.findViewById(R.id.ll_dot_layout);
        dotLayout.setVisibility(View.VISIBLE);
        mSwitcher.setDotLayout(dotLayout);
        List<String> imageUrls = new ArrayList();
        String originUrls[] = mArticle.getImgurls().split(",");
        if(originUrls.length>0&&originUrls[0]!=null&&!originUrls[0].equals("")){
            for (String url : originUrls) {
                imageUrls.add(Constant.IMAGE_PREFIX + url);
            }
            mSwitcher.setShowIndicator(true);
            mSwitcher.setImages(imageUrls);
        }
        if (imageUrls.size()==0){
            mSwitcher.setVisibility(View.GONE);
        }else {
            mSwitcher.setVisibility(View.VISIBLE);
        }

    }

    @Override
    protected RecyclerView.Adapter createAdapter() {
        ArticleDetailListItemAdapter adapter = new ArticleDetailListItemAdapter(mContext, mData);
        adapter.setListener(this);
        adapter.setOnHeadCLickLinstener(new ArticleDetailListItemAdapter.OnHeadCLickLinstener() {
            @Override
            public void onHeadClick(User user) {
                if(user==null){
                    return;
                }
                startActivity(new Intent(mContext, PersonArticleActivity.class)
                        .putExtra("user", user));

            }
        });
        return adapter;
    }

    @Override
    protected void requestData() {
        if(mArticle==null){
            return;
        }
        mPresenter.getArticleById(mArticle.getId());
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.iv_image:
                try {
                    int index = (Integer) v.getTag(R.id.position);
                    if (mArticle.isVideo()) {
//                            VideoActivity.start(mContext, Constant.IMAGE_PREFIX + mArticle.getVideoUrl());
                    } else {
                        String images[] = mArticle.getImgurls().split(",");
                        ArrayList<String> imageList = new ArrayList();
                        for (String str : images) {
                            imageList.add(Constant.IMAGE_PREFIX + str);
                        }
                        ImageActivity.start(mContext, images[index], imageList,index, null);
                    }
                } catch (Exception e) {
                }
                break;
            case R.id.image_switcher:
                int index = mSwitcher.getPosition();
                String images[] = mArticle.getImgurls().split(",");
                ArrayList<String> imageList = new ArrayList();
                for (String str : images) {
                    imageList.add(Constant.IMAGE_PREFIX + str);
                }
                Log.w("shujuxuanze",""+index);
                ImageActivity.start(mContext, images[index], imageList,index, null);
                break;
            case R.id.rl_comment_layout:
                int commentId = (Integer) v.getTag(R.id.data);
                CommentDialog dialog = new CommentDialog(mContext);
                dialog.setSendListener(this);
                dialog.setHint("回复", commentId);
                dialog.show();
                break;
            case R.id.tv_follow:
                if(mArticle==null){
                    return;
                }
                mPresenter.followArticle(mArticle.getId());
                break;
            case R.id.tv_left:
            case R.id.tv_right:
                if(mArticle==null){
                    ToastUtils.showToast(getActivity(),"抱歉，没有文章了");
                    return;
                }
                isClick=true;
                mPresenter.next(mArticle.getId(), v.getId() == R.id.tv_left ? 1 : 2);
                break;
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if(newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE){
        }else {
            getActivity().finish();
            getActivity().overridePendingTransition(0, 0);
            startActivity(new Intent(mContext, ArticleDetailActivity.class).putExtra("article", mArticle));
        }

    }


    private boolean isClick=false;

    @OnClick(R.id.tv_praise)
    public void praise() {
        mPresenter.praise(mArticle.getId());
    }

    @OnClick(R.id.tv_comment)
    public void comment() {
        CommentDialog dialog = new CommentDialog(mContext);
        dialog.setSendListener(this);
        dialog.setHint("评论", -1);
        dialog.show();
    }

    @OnClick(R.id.tv_collect)
    public void collect() {
        mPresenter.collect(mArticle.getId());
    }

    @Override
    protected void setEmptyDataView() {
//        mEmptyView.setVisibility(View.VISIBLE);
//        mEmptyView.setState(EmptyView.State.NO_DATA, "");
    }

    @Override
    public void onRequestSuccess(Article article) {
        super.onRequestSuccess(article);
        if(article==null){
            ToastUtils.showToast(getActivity(),"抱歉，没有文章了");
            return;
        }
        if(isClick==true){
            isClick=false;
            getActivity().finish();
            getActivity().overridePendingTransition(0, 0);
            startActivity(new Intent(mContext, ArticleDetailActivity.class).putExtra("article", article));
        }
        mArticle = article;
        bindData();
        mData.clear();
        List<Comment> list = mPresenter.getCommentList(article);
        if (list != null) {
            mData.addAll(list);
        }
        showListView();
    }

    @Override
    protected boolean resolveData(Article article) {
        return false;
    }

    @Override
    protected void initData() {
    }

    @Override
    protected void itemClicked(int position, Comment data) {

    }

    @Override
    protected boolean canLoadMoreItems() {
        return false;
    }

    @Override
    public void send(String content, int id) {
        if (!TextUtils.isEmpty(content)) {
            if (id != -1) {
                mPresenter.reply(mArticle.getId(), id, content);
            } else {
                mPresenter.comment(mArticle.getId(), content);
            }
        }
    }

    @Override
    public void onFollowSuccess() {
        boolean hasFollow = mArticle.isHasFollowCircle();
        hasFollow = !hasFollow;
        mArticle.setHasFollowCircle(hasFollow);
        mFollowView.setText(hasFollow ? "已关注" : "关注");
        mFollowView.setActivated(hasFollow);
        mFollowView.setTextColor(Color.parseColor(hasFollow ? "#ffb9bdd2" : "#ff00c08d"));
    }

    @Override
    public void onPraiseSuccess() {
        if (mArticle.isHasLike()) {
            mArticle.setLike(Math.max(mArticle.getLike() - 1, 0));
            mArticle.setHasLike(false);
        } else {
            mArticle.setLike(mArticle.getLike() + 1);
            mArticle.setHasLike(true);
        }
        mPraiseView.setText(String.valueOf(mArticle.getLike()));
        mPraiseView.setCompoundDrawables(mArticle.isHasLike() ? mPraised : mPraise, null, null, null);
    }

    @Override
    public void onCollectSuccess() {
        if (mArticle.isHasCollection()) {
            mArticle.setCollectionCount(Math.max(mArticle.getCollectionCount() - 1, 0));
            mArticle.setHasCollection(false);
        } else {
            mArticle.setCollectionCount(mArticle.getCollectionCount() + 1);
            mArticle.setHasCollection(true);
        }
        mCollectView.setText(String.valueOf(mArticle.getCollectionCount()));
        mCollectView.setCompoundDrawables(mArticle.isHasCollection() ? mCollected : mCollect, null, null, null);
    }

    @Override
    public void onCommentSuccess(Article art) {
        if(mArticle==null){
            return;
        }
            getActivity().finish();
            getActivity().overridePendingTransition(0, 0);
            startActivity(new Intent(mContext, ArticleDetailActivity.class).putExtra("article", mArticle));

    }
}
